import Ember from 'ember';
import menuFilter from 'emberworkspace/utils/menu-filter';
import hateoasJsonapi from 'emberworkspace/utils/hateoas-jsonapi';


export default Ember.Service.extend({
  user: null,
  menuLinks: [],
  isManager: function() {
    return this.hasRole("ROLE_USER_MANAGER");
  },
  hasRole: function(r) {
    var user = this.get('user'),
      roles = user && user.get('roles');
    if (roles) {
      return roles.any(function(lr) {
        return lr.get('name') === r;
      });
    }
  },
  hasAnyRole: function(rs) {
    var self = this;
    if (!rs) {
      return false;
    }
    if (Ember.typeOf(rs) === 'string') {
      return self.hasRole(rs);
    }
    return rs.any((it) => {
      return self.hasRole(it);
    });
  },
  initMe: function(store, myGlobals, data) {
    var logined = data.logined,
      user = data.user,
      myRoles = user ? user.roles : [],
      allRoles = data.allRoles || [],
      myRoleRecords,
      userRecord,
      rolesInStore;

    if (logined) {
      //把role全部压入store.
      allRoles.forEach((it) => {
        store.push(hateoasJsonapi("role", it));
      });

      myGlobals.set('roles', store.peekAll("role"));

      if (allRoles.length === 0) {
        myRoles.forEach((it) => {
          store.push(hateoasJsonapi("role", it));
        });
      }

      myRoleRecords = myRoles.map((it) => {
        return store.peekRecord("role", it.id);
      });

      this.set('user', store.push(hateoasJsonapi("person", user)));
      // this.get('user').get('roles').forEach((it) => {
      //   console.log(it.get('name'));
      // });

      if (this.hasRole('ROLE_USER_MANAGER')) {
        console.log("i am manager.");
      }
    }
    this.set('menuLinks', menuFilter(this.get('user')));
    return this;
  }
});
